package com.usefullc.system.log;

import com.usefullc.common.user.OnlineUser;
import com.usefullc.common.user.OnlineUserManager;
import com.usefullc.common.util.JsonUtil;
import com.usefullc.common.util.RequestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.web.filter.CommonsRequestLoggingFilter;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author: Sampson
 * @date: 2021-05-25 11:22
 */
//@Configuration
public class ReqLogFilter extends CommonsRequestLoggingFilter {

    Long startTime;
    Long endTime;

    private static Map<String,Boolean> playLoadMap = new HashMap<>();

    public static void putPlayLoad(String url,Boolean playload){
        playLoadMap.put(url,playload);
    }

    public ReqLogFilter(){
//        super.setIncludeClientInfo(true);
//        super.setIncludeQueryString(true);
//        super.setIncludePayload(true);
//        super.setMaxPayloadLength(20000);

    }

    @Override
    protected void beforeRequest(HttpServletRequest request, String message) {
        MDC.put("traceId", UUID.randomUUID().toString());
//        Thread.currentThread().getId();
        startTime = System.currentTimeMillis();
        String requestURI = request.getRequestURI();
        while(StringUtils.removeStart(requestURI,"/").startsWith("/")){
            requestURI = "/"+requestURI;
        }
        Boolean playLoad = playLoadMap.get(requestURI);
        if(playLoad != null){
            super.setIncludePayload(playLoad);
        }
//        User user = userService.getLoginUser(request);
//        String userJson = JsonUtil.bean2Json(user);
//        message = "tid="+Thread.currentThread().getId()+",User:"+userJson + "\n"+message;
//        super.beforeRequest(request, message);
    }

    @Override
    protected void afterRequest(HttpServletRequest request, String message) {
        endTime = System.currentTimeMillis();
        String takeTime = "\ttake time="+(endTime-startTime)+" ms";
        OnlineUser user = OnlineUserManager.getLoginUser();
        String userJson = JsonUtil.bean2Json(user);
        message = "User:"+userJson +"\t"+"realClient="+ RequestUtils.getClientIpAddr(request)+"," +message + takeTime;
        super.afterRequest(request, message);
        MDC.clear();
    }
}
